<?php

namespace app\controller;

use think\db\exception\DbException;
use think\facade\Db;
use think\response\Json;

/**
 * 数据库测试
 */
class Dbtest
{
    /**
     * 测试插入数据
     * @return Json
     */
    public function testInsert(): Json
    {
        $data = [
            'name' => 'test',
            'age' => 18,
            'sex' => 1,
            'remarks' => __CLASS__ . '\\' . __FUNCTION__,
        ];
        $res = Db::name('test')->insert($data);
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试删除数据
     * @return Json
     * @throws DbException
     */
    public function testDelete(): Json
    {
        $res = Db::name('test')->where('_id', '=', '65cd921bcbc6443eab022d60')->delete();
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试更新数据
     * @return Json
     * @throws DbException
     */
    public function testUpdate(): Json
    {
        $data = [
            'age' => 28,
        ];
        $res = Db::name('test')->where('_id', '=', '65cd92bdb0e8da2f6d032330')->update($data);
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试查询数据
     * @return Json
     * @throws DbException
     */
    public function testFind(): Json
    {
        $res = Db::name('test')->where('_id', '=', '65cd92bdb0e8da2f6d032330')->find();
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试查询数据
     * @return Json
     * @throws DbException
     */
    public function testSelect(): Json
    {
        $res = Db::name('test')->select();
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试count数据
     * @return Json
     * @throws DbException
     */
    public function testCount(): Json
    {
        $res = Db::name('test')->count();
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试分页数据
     * @return Json
     * @throws DbException
     */
    public function testPage(): Json
    {
        $res = Db::name('test')->page(1, 10)->select();
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }

    /**
     * 测试分页数据
     * @return Json
     * @throws DbException
     */
    public function testPaginate(): Json
    {
        $res = Db::name('test')
            ->where('age', '=', 18)
            //->order(['age' => -1])
            ->order('$natural', 'desc')
            ->paginate(10);
        $sql = Db::getLastSql();
        return json(['res' => $res, 'sql' => $sql]);
    }
}